using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using MvcExtExample.Models;
using Newtonsoft.Json;

namespace MvcExtExample.Handlers
{
    /// <summary>
    /// Summary description for DeptOperation
    /// </summary>
    public class DeptOperation : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string act = context.Request.Params["act"] ?? "";
            string output = "";
            switch (act.ToLower())
            {
                case "add":
                    output = Add(context.Request);
                    break;
                case "del":
                    output = Del(context.Request);
                    break;
                case "edit":
                    output = Edit(context.Request);
                    break;
                case "read":
                    output = Read(context.Request);
                    break;
                default:
                    output = "{'success':false,'msg':'错误的操作类型'}";
                    break;
            }
            context.Response.ContentType = "text/javascript";
            context.Response.Write(output);
        }

        private string Read(HttpRequest httpRequest)
        {
            int start = 0;
            int.TryParse(httpRequest.Params["start"], out start);
            framework.JSONHelper jsonHelp = new framework.JSONHelper();
            int TotalRecords = 0;
            string total = "SELECT COUNT(*) FROM [dbo].[Tb_Department]";
            string strSqlStr = "SELECT TOP 18 * FROM [Tb_Department] WHERE Dep_ID NOT IN ( SELECT TOP " + start + " Dep_ID FROM [Tb_Department]   ORDER BY Dep_ID ) ORDER BY Dep_ID";
            framework.SqlHelperCS.SqlHelper cs = new framework.SqlHelperCS.SqlHelper();
            TotalRecords = cs.ReturnSQL(total);
            DataSet DSet = cs.GetDataSet(strSqlStr);
            if (DSet != null)
            {
                DataTable dt = DSet.Tables[0];
                StringBuilder JsonString = new StringBuilder();
                if (dt != null && dt.Rows.Count > 0)
                {
                    JsonString.Append("{\"total\":" + TotalRecords + ",\"data\":[ ");
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        JsonString.Append("{ ");
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            if (j < dt.Columns.Count - 1)
                            {
                                JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\"" + ":" + "\"" + dt.Rows[i][j].ToString() + "\",");
                            }
                            else if (j == dt.Columns.Count - 1)
                            {
                                JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\"" + ":" + "\"" + dt.Rows[i][j].ToString() + "\"");
                            }
                        }

                        if (i == dt.Rows.Count - 1)
                        {
                            JsonString.Append("} ");
                        }
                        else
                        {
                            JsonString.Append("}, ");
                        }
                    }
                    JsonString.Append("]}");
                    return JsonString.ToString();
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        private string Edit(HttpRequest httpRequest)
        {
            string data = httpRequest.Params["data"] ?? "";
            List<Department> logs = new List<Department>();
            if (data.Length > 0)
            {
                logs = ProcessData(data);
                try
                {
                    foreach (Department item in logs)
                    {
                        string sql = "UPDATE [dbo].[Tb_Department] SET [Dep_Name]='" + item.Dep_Name + "',ParentDep_ID='" + item.ParentDep_ID + "' WHERE [Dep_ID]='" + item.Dep_ID + "'";
                        framework.SqlHelperCS.SqlHelper cs = new framework.SqlHelperCS.SqlHelper();
                        cs.RunSQL(sql);
                    }
                    return "{'success':true}";
                }
                catch (Exception e)
                {
                    return "{'success':false,'Msg':'" + e.Message + "'}";
                }
            }
            else
            {
                return "{'success':false,'Msg':'错误的提交数据！'}";
            }
        }

        private string Add(HttpRequest httpRequest)
        {
            string data = httpRequest.Params["data"] ?? "";
            List<Department> logs = new List<Department>();
            if (data.Length > 0)
            {
                logs = ProcessData(data);
                try
                {
                    foreach (Department item in logs)
                    {
                        string sql = "INSERT INTO [dbo].[Tb_Department] ([Dep_ID],[Dep_Name],[ParentDep_ID]) VALUES('"+item.Dep_ID+"',N'"+item.Dep_Name+"','"+item.ParentDep_ID+"')";
                        framework.SqlHelperCS.SqlHelper cs = new framework.SqlHelperCS.SqlHelper();
                        cs.RunSQL(sql);
                    }
                    return "{'success':true}";
                }
                catch (Exception e)
                {
                    return "{'success':false,'Msg':'" + e.Message + "'}";
                }
            }
            else
            {
                return "{'success':false,'Msg':'错误的提交数据！'}";
            }
        }

        private string Del(HttpRequest httpRequest)
        {
            string data = httpRequest.Params["data"] ?? "";
            List<Department> logs = new List<Department>();
            if (data.Length > 0)
            {
                logs = ProcessData(data);
                try
                {
                    foreach (Department item in logs)
                    {
                        string sql = "DELETE FROM [dbo].[Tb_Department] WHERE [Dep_ID]='" + item.Dep_ID + "'";
                        framework.SqlHelperCS.SqlHelper cs = new framework.SqlHelperCS.SqlHelper();
                        cs.RunSQL(sql);
                    }
                    return "{'success':true}";
                }
                catch (Exception e)
                {
                    return "{'success':false,'Msg':'" + e.Message + "'}";
                }
            }
            else
            {
                return "{'success':false,'Msg':'错误的提交数据！'}";
            }
        }

        private List<Department> ProcessData(string data)
        {
            List<Department> logs = new List<Department>();
            logs = JsonConvert.DeserializeObject<List<Department>>(data);
            return logs;
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}